import 'dart:async';
import 'dart:io';

import 'package:fbroadcast/fbroadcast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
import 'package:tiktokadult/hj_page/video/video_full_page.dart';
import 'package:tiktokadult/hj_page/video/view/detail_top_right_view.dart';
import 'package:tiktokadult/hj_utils/screen.dart';

import '../../alert_business/video/comic_buy_alert.dart';
import '../../alert_business/video/newer_vip_alert.dart';
import '../../alert_business/video/vip_dailog.dart';
import '../../config/config.dart';
import '../../hj_model/acg/comic_chapters_model.dart';
import '../../hj_model/cartoon_media_info.dart';
import '../../hj_model/media_content.dart';
import '../../hj_model/splash/ads_model.dart';
import '../../hj_model/video_model.dart';
import '../../hj_utils/api_service/acg_service.dart';
import '../../hj_utils/api_service/vid_service.dart';
import '../../hj_utils/event_tracking_manager.dart';
import '../../hj_utils/free_play_count_manager.dart';
import '../../hj_utils/global.dart';
import '../../hj_utils/history_record_util.dart';
import '../../hj_utils/light_model.dart';
import '../../hj_utils/player_util.dart';
import '../../routers/jump_router.dart';
import '../../tools_base/debug_log.dart';
import '../../tools_base/event_bus/events.dart';
import '../../tools_base/global_store/local_ads_info_store.dart';
import '../../tools_base/global_store/store.dart';
import '../../tools_base/video_download/video_download_manager.dart';
import '../main_page/provider/msg_provider.dart';
import '../pre_sale/pre_sale_provider.dart';
import 'cartoon/model_exchange.dart';

class VideoLogic extends GetxController {

  final String? vid;
  bool isCartoon;
  VideoLogic({this.vid, this.isCartoon = false});

  VideoModel? videoModel;
  String? videoUrl;

  String? get videoCover => videoModel?.cover;
  VideoPlayerController? videoPlayerController;
  List<AdsInfoModel> videoAdsList = [];
  bool alreadyShowDialog = false;
  int duration = 0;
  bool isToVipPage = false; //true: 视频广告，点击跳转到vip页面
  bool hasVideoAd = false; // true: 视频广告还在显示中
  bool isShowVideoAd = false; // true： 显示视频广告
  bool isFullScreen = false; // true:视频进入全屏页面
  bool isPlayLocalCacheVideo = false; // 播放缓存视频
  RxBool isShowBuyView = false.obs; // 显示购买和vip弹窗

  List<dynamic> tagsName = [];

  ScrollController scrollController = ScrollController();
  PageController pageController = PageController();
  CartoonMediaInfo? cartoonModel; //动漫
  ComicChapterInfo? currentEpisode; //动漫集数

  bool isDispose = false;
  LongVideStatus get videoStatus => longVideoStatusDesc(videoModel);
  bool get isVipCoinFree {
    if (videoModel?.isCoinVideo() != true) {
      // 非金币视频
      return false;
    }
    if (globalStore.isVIP() && videoModel?.coins == 0) {
      // vip金币视频 免看
      return true;
    } else {
      if (isCartoon == true) return false; // 动漫视频不享受金币免次数权益
      if (presaleProvider.coinVideoFreeCount >= 0) return true;
      return false;
    }
  }

  bool get initedVideoController => videoPlayerController?.value.isInitialized == true; //视频控制器是否加载
  double get normalRatio => 16 / 9;

  double get videoRatio {
    if (isCartoon) {
      return normalRatio;
    } else if (initedVideoController) {
      return videoPlayerController!.value.aspectRatio;
    } else {
      return normalRatio;
    }
  }

  @override
  void onInit() {
    onInitData();
    FBroadcast.instance().register(SWITCH_CDN_ADDRESS, _switchLineEvent);
    super.onInit();
    alertVipFirst();
  }

  void alertVipFirst() async {
    bool isFirst = await MineMsgProvider.isShowNewerAlertFirst();
    if(MineMsgProvider().newerTime > 0 && isFirst && Config.recommendVipIds?.isNotEmpty == true && !GlobalStore().isVIP()) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async{
        await Get.dialog(NewerVipAlert());
        MineMsgProvider.isShowNewerAlertFinish();
      });
    }
  }

  // exchangeId: 有值 是视频内切换集数或者切换视频
  Future onInitData({String? exchangeId}) async {
    try {
      if (isCartoon == true) {
        cartoonModel = await ACGService.getMediaInfo(exchangeId ?? videoModel?.id ?? vid ?? "");
        int currentPage = cartoonModel?.episodeCurPage ?? 0;
        final episodeModel = await ACGService.mediaContentChapterList(
          exchangeId ?? videoModel?.id ?? vid ?? "",
          currentPage + 1,
          cartoonModel?.episodePageSize ?? 40,
          sortType: cartoonModel?.isUpSort,
        );
        cartoonModel?.episodeList = episodeModel?.list;
        if (episodeModel?.list?.isNotEmpty != true) {
          showToast("资源配置错误～");
          Get.back();
          return;
        }
        cartoonModel?.episodeCurPage = currentPage + 1;
        cartoonModel?.haxNextEpisode = episodeModel?.hasNext ?? true;
        videoModel?.mediaInfo = cartoonModel;
        currentEpisode = episodeModel?.list?.first;
        MediaContent? mediaContent = await ACGService.getMediaDetailInfo(id: currentEpisode?.id ?? "");
        episodeModel?.list?.first.mediaContent = mediaContent;
        videoModel = changeData(cartoonModel, currentEpisode);
      } else {
        videoModel = await VidService.getVideoDetail(exchangeId ?? videoModel?.id ?? vid ?? "");
      }
      isShowBuyView.value = false;
      safeFlashUI();
    } catch (e) {
      debugLog(e.toString());
    }
    if (isCartoon == true) {
      HistoryRecordUtil.insertHistoryModel<CartoonMediaInfo>(videoModel!.mediaInfo!, HistoryRecordType.cartoon);
    } else {
      HistoryRecordUtil.insertHistoryModel<VideoModel>(videoModel!, HistoryRecordType.video);
    }
    hasVideoAd = false;
    _initVideoData();
    videoModel!.tags!.map((e) {
      tagsName.add(e.name);
    });

    FBroadcast.instance().register("refreshLongVideoStatus", _reLoadVideoPlayStatus);
  }

  // 切换集数
  void exchangeEpisod(ComicChapterInfo selectModel) async {
    if (selectModel.id == currentEpisode?.id) {
      showToast("正在播放");
      return;
    } else {
      try {
        currentEpisode = selectModel;
        isShowBuyView.value = false;
        releaseVideoController(isRelease: true);
        update();
        if (currentEpisode?.mediaContent == null) {
          currentEpisode?.mediaContent = await ACGService.getMediaDetailInfo(id: currentEpisode?.id ?? "");
        }
        VideoModel model = changeData(cartoonModel, currentEpisode);
        startVideoPlayer(model: model);
      } catch (e) {
        debugLog(e);
      }
    }
  }

  void _reLoadVideoPlayStatus(value, callback) {
    alreadyShowDialog = false;
    videoModel?.vidStatus?.hasPaid = true;
    startVideoPlayer();
    safeFlashUI();
  }

  Future<bool> safeFlashUI() async {
    update();
    return true;
  }

  void _switchLineEvent(context, value) {
    // 路线切换
    if (!isPlayLocalCacheVideo) {
      startVideoPlayer();
      safeFlashUI();
    }
  }

  void setNoAdVideo() {
    isShowVideoAd = false;
    hasVideoAd = false;
  }

  void videoPlay() {
    if (isToVipPage == true) {
      return;
    } else {
      videoPlayerController?.play();
    }
  }

  // 全屏事件
  void toFullPage() async {
    if (hasVideoAd || videoPlayerController?.value.isInitialized != true) {
      return;
    }
    isFullScreen = true;
    await Get.to(VideoFullPage(controller: videoPlayerController!, videoModel: videoModel));
    isFullScreen = false;
  }

  /// 推出全屏
  void backFullScreenEvent() {
    if (isFullScreen) {
      isFullScreen = false;
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: [SystemUiOverlay.bottom, SystemUiOverlay.top]);
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
      Get.back();
    }
  }

  void clickAdToVip() async {
    bool isPlaying = videoPlayerController?.value.isPlaying ?? false;
    videoPlayerController?.pause();
    isToVipPage = true;
    await jumpToWalletPage(tabPosition: isCartoon ? 1 : 0);
    isToVipPage = false;
    if (isPlaying) {
      videoPlay();
    }
    await globalStore.updateUserInfo();
    if (globalStore.isVIP()) {
      safeFlashUI();
    }
  }

  /// 初始化数据
  void _initVideoData({int prePostion = 0}) async {
    FreePlayCountManager().canFreePlay(videoModel);
    videoAdsList = await getAdvByType(8);
    if (Config.adsTimeLongVideo > 0 && videoAdsList.isNotEmpty == true) {
      if (videoModel?.vidStatus?.hasPaid == true) {
        setNoAdVideo(); // 购买的视频不显示广告
      } else if (globalStore.isVIP() && !videoStatus.isNeedBuy) {
        setNoAdVideo();
      }
    } else {
      setNoAdVideo();
    }
    if (videoModel?.localPath?.isNotEmpty != true && globalStore.isVIP()) {
      dynamic result = await VideoDownloadManager.instance.searchInfo(
        url: videoModel?.realVideoUrl,
      );
      if (result is Map) {
        Map fileInfoMap = result;
        String? filePath = fileInfoMap["localPath"];
        if (filePath?.isNotEmpty == true) {
          videoModel?.localPath = filePath;
        }
      }
    }
    int? playContentStyle = videoModel?.playContentStyle;
    if (playContentStyle == 2 && videoModel?.chineseLink?.isNotEmpty == true) {
      videoUrl = videoModel?.realChineseUrl;
    } else if (playContentStyle == 3 && videoModel?.codelessLink?.isNotEmpty == true) {
      videoUrl = videoModel?.realUncodeUrl;
    } else if (isCanPlayPreviewVideo()) {
      videoUrl = videoModel?.realPreviewUrl;
    } else {
      videoUrl = videoModel?.realVideoUrl;
    }
    if (videoModel?.localPath?.isNotEmpty == true) {
      isPlayLocalCacheVideo = true;
      videoPlayerController = VideoPlayerController.file(File(videoModel?.localPath ?? ""));
    } else {
      videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(videoUrl ?? ""));
      isPlayLocalCacheVideo = false;
      //showToast( "切换成功的线路是 $videoUrl");
    }
    try {
      await videoPlayerController?.initialize();
      safeFlashUI();
    } catch (e) {
      isPlayLocalCacheVideo = false;
      debugLog("视频初始化失败：$e   play url = $videoUrl");
      showToast("视频资源加载失败!");
      return;
    }
    if (isDispose) {
      videoPlayerController?.pause();
      videoPlayerController?.dispose();
      return;
    }
    if (videoRatio < normalRatio) {
      double offset = screen.screenWidth / videoRatio - screen.screenWidth / normalRatio;
      scrollController = ScrollController(initialScrollOffset: offset);
      safeFlashUI();
    }
    presaleProvider.consumeVCoinPrivilegeCount(videoModel);
    duration = videoPlayerController?.value.duration.inSeconds ?? 0;
    videoPlayerController?.addListener(_listenCallback);
    int previewStart = videoModel?.previewStart ?? 0;
    if (previewStart > 0) {
      bool needBuyVipBool = videoStatus.isNeedVip;
      bool needBuyVideoBool = videoStatus.isNeedBuy;
      if (FreePlayCountManager().canFreePlay(videoModel) || videoModel?.freeArea == true) {
        //免金币视频 / 有免费观看次数(vip视频)
        print('免金币视频 / 有免费观看次数(vip视频)');
      } else if (needBuyVipBool || needBuyVideoBool) {
        await videoPlayerController?.seekTo(Duration(seconds: previewStart));
      } else {}
    } else if (prePostion > 2) {
      await videoPlayerController?.seekTo(Duration(seconds: prePostion));
    }
    videoPlay();
    safeFlashUI();
  }

  void _listenCallback() async {
    if (FreePlayCountManager().canFreePlay(videoModel)) return;
    if (videoModel?.freeArea == true) return;
    if (cartoonModel?.mediaStatus?.hasPaid == true) return; // 动漫整本解锁, 都可以看, 不管vip权限
    if (isVipCoinFree) return; // vip 金币视频限免
    if (!isCanPlayPreviewVideo()) {
      bool needBuyVipBool = videoStatus.isNeedVip;
      bool needBuyVideoBool = videoStatus.isNeedBuy;
      if (isFullScreen == true) {
        if (videoModel?.isFreeTimeGroup(videoPlayerController!.value.position.inSeconds) == true) {
        } else {
          if (needBuyVipBool || needBuyVideoBool) {
            if (videoPlayerController?.value.isPlaying == true) {
              backFullScreenEvent();
            }
          }
        }
      }

      //检查免费时间,是否需要弹出金币购买视频
      if (videoModel?.isFreeTimeGroup(videoPlayerController!.value.position.inSeconds) != true && needBuyVideoBool) {
        if (videoPlayerController?.value.isPlaying == true) {
          _buyEvent();
        }
      } else {
        if ((videoPlayerController!.value.position.inSeconds) > ((duration) * 0.1)) {
          EventTrackingManager().addVideoDatas(videoModel?.id, videoModel?.title);
        }
      }
      //检查免费时间,是否需要弹出会员购买视频
      if (videoModel?.isFreeTimeGroup(videoPlayerController!.value.position.inSeconds) != true && needBuyVipBool) {
        if (videoPlayerController?.value.isPlaying == true) {
          // 买了之后怎么通知
          onShowVipDialog();
        }
      } else {
        if (videoPlayerController!.value.position.inSeconds > ((duration) * 0.1)) {
          EventTrackingManager().addVideoDatas(videoModel?.id, videoModel?.title);
        }
      }
    } else {
      //预览视频逻辑处理
      if (videoPlayerController!.value.position.inSeconds == duration - 1) {
        await videoPlayerController!.seekTo(const Duration(milliseconds: 0));
        videoPlayerController?.pause();
        if (isFullScreen == true) {
          backFullScreenEvent();
        }
        Future.delayed(const Duration(milliseconds: 200), () async {
          if (videoModel?.coins != 0) {
            _buyEvent();
          } else if (videoModel?.coins == 0 && videoModel?.freeArea != true) {
            ///点击的必须弹出
            if (!alreadyShowDialog) {
              alreadyShowDialog = true;
              await onShowVipDialog();
              alreadyShowDialog = false;
              await globalStore.updateUserInfo();
              if (globalStore.isVIP()) {
                startVideoPlayer();
                safeFlashUI();
              } else {
                videoPlayerController?.play();
              }
            }
          }
        });
      }
    }
  }

  void showBuyMask() async {
    videoPlayerController?.pause();
    isShowBuyView.value = true;
    safeFlashUI();
    // if (isCartoon) {
    //   if (videoModel?.mediaInfo?.permission == 1) {
    //     var result = await ComicBuyAlert.show(mediaInfo: videoModel?.mediaInfo);
    //
    //     ///true表示支付成功
    //     if (result == 1 || result == 2) {
    //       videoModel?.vidStatus?.hasPaid = true;
    //       currentEpisode?.hasBuy = true;
    //       if (result == 2) {
    //         // 全集购买
    //         videoModel?.mediaInfo?.mediaStatus?.hasPaid = true;
    //       }
    //       videoPlayerController?.play();
    //     }
    //     safeFlashUI();
    //   } else {
    //     await Get.dialog(VipDialog());
    //   }
    // }
  }

  /// 购买会员
  Future onShowVipDialog() async {
    showBuyMask();
    if (presaleProvider.isOpen && presaleProvider.hasLimit == false) {
      await Get.dialog(const VipDialog(presale: true));
    }
  }

  bool isCanPlayPreviewVideo() {
    if (FreePlayCountManager().canFreePlay(videoModel) == true) {
      return false;
    }
    if (videoModel?.previewURL?.isNotEmpty == true && (videoStatus.isNeedBuy || videoStatus.isNeedVip)) {
      return true;
    } else {
      return false;
    }
  }

  // 推荐，点击切换动漫视频
  Future<void> exchangeCartoonPlayer(VideoModel model) async {
    videoModel = model;
    isShowBuyView.value = false;
    final oldVideoPlayerController = videoPlayerController;
    oldVideoPlayerController?.pause();
    oldVideoPlayerController?.removeListener(_listenCallback);
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      oldVideoPlayerController?.dispose();
    });
    onInitData(exchangeId: model.id);
    videoPlayerController = null;
    safeFlashUI();
  }

  // 推荐，点击切换视频 (isExchange true 切换视频)
  Future<void> startVideoPlayer({VideoModel? model}) async {
    if (model != null) {
      videoModel = model;
    }
    if (videoPlayerController == null) {
      _initVideoData();
    } else {
      releaseVideoController(model: model);
      safeFlashUI();
    }
  }

  //isRelease: true, 只释放播放器，不做其他逻辑
  void releaseVideoController({VideoModel? model, bool isRelease = false}) {
    final oldVideoPlayerController = videoPlayerController;
    oldVideoPlayerController?.pause();
    int prePostion = oldVideoPlayerController?.value.position.inSeconds ?? 0;
    oldVideoPlayerController?.removeListener(_listenCallback);
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      oldVideoPlayerController?.dispose();
      if (!isRelease) {
        if (model != null) {
          isShowBuyView.value = false;
          safeFlashUI();
          onInitData(exchangeId: model.id);
        } else {
          _initVideoData(prePostion: prePostion);
        }
      }
    });
    videoPlayerController = null;
  }

  void _buyEvent() async {
    showBuyMask();
    // videoPlayerController?.pause();
    // if (isCartoon) {
    //   var result = await ComicBuyAlert.show(
    //     mediaInfo: videoModel?.mediaInfo?.updateStatus == 1 ? null : videoModel?.mediaInfo,
    //     curModel: currentEpisode,
    //   );
    //   ///true表示支付成功
    //   if (result == 1 || result == 2) {
    //     videoModel?.vidStatus?.hasPaid = true;
    //     currentEpisode?.hasBuy = true;
    //     if (result == 2) {
    //       // 全集购买
    //       videoModel?.mediaInfo?.mediaStatus?.hasPaid = true;
    //     }
    //     videoPlayerController?.play();
    //   }
    //   safeFlashUI();
    // } else {
    //   // 预售开启期间,未购买
    //   bool hasPresaleActivity = presaleProvider.isOpen && !presaleProvider.isPayAll(); //有预售活动
    //   if (Get.isDialogOpen == true && !presaleProvider.isOpen) return;
    //   var result = await Get.bottomSheet(VideoBuyBottomSheet(videoM: videoModel!, presale: hasPresaleActivity));
    //   // true表示支付成功  1 购买单集  2 购买全集
    //   if (result == true) {
    //     videoModel?.vidStatus?.hasPaid = true;
    //     videoModel?.mediaInfo?.mediaStatus?.hasPaid = true;
    //     if (isCanPlayPreviewVideo()) {
    //       // 购买后，如果是预览视频，重新刷新播放链接
    //       startVideoPlayer();
    //     } else {
    //       videoPlayerController?.play();
    //     }
    //     safeFlashUI();
    //   }
    // }
  }

  @override
  void onClose() {
    videoPlayerController?.pause();
    videoPlayerController?.removeListener(_listenCallback);
    FBroadcast.instance().remove(_switchLineEvent, key: SWITCH_CDN_ADDRESS);
    FBroadcast.instance().remove(_reLoadVideoPlayStatus, key: "refreshLongVideoStatus");
    if (videoPlayerController != null) {
      bool isPreview = false;
      if (videoModel?.previewURL?.isNotEmpty == true) {
        if (videoPlayerController?.dataSource.contains(videoModel?.previewURL ?? "") == true) {
          isPreview = true;
        }
      }
      if (!isPreview) {
        try {
          List<String> tagsName = [];
          videoModel?.tags?.map((e) {
            tagsName.add(e.name ?? "");
          });
          EventTrackingManager.uploadEvent("视频记录", eventProperties: {
            // "跳转路由": widget.linkRoute,
            "视频类型": "长视频",
            "用户身份": globalStore.isVIP() ? "VIP" : "非VIP",
            "标题": videoModel!.title.toString(),
            "id": videoModel!.id.toString(),
            "标签": tagsName.toString(),
            "价格": videoModel!.coins,
            "是否VIP视频": videoModel!.coins == 0 ? "是" : "否",
            "播放量": videoModel!.playCount,
            "点赞量": videoModel!.likeCount,
            "收藏量": videoModel!.collectCount,
            "评论量": videoModel!.commentCount,
            "总时长": "${videoPlayerController?.value.duration.inSeconds}秒",
            "当前播放时长": "${videoPlayerController?.value.position.inSeconds}秒",
            "当前播放进度":
                "${((videoPlayerController!.value.position.inMilliseconds / videoPlayerController!.value.duration.inMilliseconds) * 100).toInt()}%",
          });

          sendRecord(videoPlayerController?.value.position, videoPlayerController?.value.duration, videoModel);
        } catch (e) {
          debugLog(e);
        }
      }
    }
    videoPlayerController?.dispose();
    videoPlayerController = null;
    isDispose = true;
    super.onClose();
  }
}
